🧠Почему context.WithCancel может вызвать утечку goroutine
context.WithCancel — удобный способ завершать операции, но если не вызывать cancel(), вы получите утечку. Причём не всегда это очевидно.
Посмотрим:
func handler(w http.ResponseWriter, r *http.Request) { ctx, cancel := context.WithCancel(r.Context()) // cancel не вызывается! go doSomething(ctx) w.Write([]byte("done")) }
func doSomething(ctx context.Context) { select { case <-time.After(10 * time.Second): fmt.Println("done work") case <-ctx.Done(): fmt.Println("canceled") } }
Что здесь не так?
Если handler завершится раньше, чем doSomething, и cancel() не вызван — doSomething останется висеть, пока не истечёт r.Context()илиtime.After. И таких горутин может накопиться много, особенно при высоких нагрузках.
💡 Как избежать
1. Всегда вызывай cancel(), когда используешь context.WithCancel, даже если кажется, что это «не нужно».
2. Если передаёшь контекст в goroutine — убедись, что она завершится, даже если вызывающая функция ушла.
context.WithCancel — мощный инструмент. Но без вызова cancel() ты легко создашь утечку, которую не поймаешь ни в логах, ни в профилях — только под нагрузкой.
🧠Почему context.WithCancel может вызвать утечку goroutine
context.WithCancel — удобный способ завершать операции, но если не вызывать cancel(), вы получите утечку. Причём не всегда это очевидно.
Посмотрим:
func handler(w http.ResponseWriter, r *http.Request) { ctx, cancel := context.WithCancel(r.Context()) // cancel не вызывается! go doSomething(ctx) w.Write([]byte("done")) }
func doSomething(ctx context.Context) { select { case <-time.After(10 * time.Second): fmt.Println("done work") case <-ctx.Done(): fmt.Println("canceled") } }
Что здесь не так?
Если handler завершится раньше, чем doSomething, и cancel() не вызван — doSomething останется висеть, пока не истечёт r.Context()илиtime.After. И таких горутин может накопиться много, особенно при высоких нагрузках.
💡 Как избежать
1. Всегда вызывай cancel(), когда используешь context.WithCancel, даже если кажется, что это «не нужно».
2. Если передаёшь контекст в goroutine — убедись, что она завершится, даже если вызывающая функция ушла.
context.WithCancel — мощный инструмент. Но без вызова cancel() ты легко создашь утечку, которую не поймаешь ни в логах, ни в профилях — только под нагрузкой.
Spiking bond yields driving sharp losses in tech stocks
A spike in interest rates since the start of the year has accelerated a rotation out of high-growth technology stocks and into value stocks poised to benefit from a reopening of the economy. The Nasdaq has fallen more than 10% over the past month as the Dow has soared to record highs, with a spike in the 10-year US Treasury yield acting as the main catalyst. It recently surged to a cycle high of more than 1.60% after starting the year below 1%. But according to Jim Paulsen, the Leuthold Group's chief investment strategist, rising interest rates do not represent a long-term threat to the stock market. Paulsen expects the 10-year yield to cross 2% by the end of the year.
A spike in interest rates and its impact on the stock market depends on the economic backdrop, according to Paulsen. Rising interest rates amid a strengthening economy "may prove no challenge at all for stocks," Paulsen said.
Telegram has exploded as a hub for cybercriminals looking to buy, sell and share stolen data and hacking tools, new research shows, as the messaging app emerges as an alternative to the dark web.An investigation by cyber intelligence group Cyberint, together with the Financial Times, found a ballooning network of hackers sharing data leaks on the popular messaging platform, sometimes in channels with tens of thousands of subscribers, lured by its ease of use and light-touch moderation.Библиотека Go Golang разработчика from id